﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using LanguageInfo.Common.Utilities;
using System.Web.Caching;
using System.Web;
using System.IO;

namespace LanguageInfo.Common.Config
{
    /// <summary>
    /// 类和xml文件相互转换的工具
    /// 作者：路晓阳
    /// 时间：2010-4
    /// </summary>
    public class ConfigHelper
    {
        /// <summary>
        /// 载入配置文件到
        /// 配置文件名:类名.config
        /// </summary>
        /// <typeparam name="T">与config对应的类型</typeparam>
        /// <returns>返回截入的配置类实例，如不能载入，返回null</returns>
        public static T Load<T>()
        {
            try
            {
                Type type = typeof(T);
                string configFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, string.Format("config\\{0}.config", type.Name));
                //string configFile = PathHelper.GetMapPath(
                //          string.Concat(ConfigurationManager.AppSettings["ConfigPath"], string.Format("{0}.config", type.Name))
                //     );

					 //Log4netHelper.Info(configFile, null);
                return (T)SerializationHelper.Load(type, configFile);

            }
            catch (System.AppDomainUnloadedException ex1)
            {
                Log4netHelper.Error("ConfigHelper Load {0} error,", ex1);
            }
            catch (Exception ex)
            {
                Log4netHelper.Error("ConfigHelper Load {0} error,", ex);
            }

            return default(T);

        }

        /// <summary>
        /// 保存配置类实例到配置文件中
        /// </summary>
        /// <typeparam name="T">配置类的类型</typeparam>
        /// <param name="config">配置类实例</param>
        public static void Save<T>(T config)
        {
            //string configFile = PathHelper.GetMapPath(
            //          string.Concat(ConfigurationManager.AppSettings["ConfigPath"], string.Format("{0}.config", typeof(T).Name))
            //     );
            Type type = typeof(T);
            string configFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, string.Format("config\\{0}.config", type.Name));
            SerializationHelper.Save(config, configFile);
        }

        /// <summary>
        /// 从系统缓存中读取配置数据
        /// 如果缓存中不存在此配置数据，则从配置文件中读取，再添加到缓存
        /// </summary>
        /// <param name="onUpdate">配置文件改变时的操作</param>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T LoadCached<T>(CacheItemRemovedCallback onUpdate)
        {
            Type type = typeof(T);
            var chahe_key = string.Format("{0}.config", type.Name);
            if (!CacheHelper.Contain(chahe_key))
            {
                //string configFile = PathHelper.GetMapPath(
                //      string.Concat(ConfigurationManager.AppSettings["ConfigPath"], string.Format("{0}.config", type.Name))
                //    );
                
                string configFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, string.Format("config\\{0}.config", type.Name));

                var config = Load<T>();
					 //Log4netHelper.Info((config==null).ToString(), null);
                var dependency = new CacheDependency(configFile);
                CacheHelper.Set(chahe_key, config, dependency, DateTime.MaxValue, Cache.NoSlidingExpiration, onUpdate);
                return config;
            }

            return (T)CacheHelper.Get(chahe_key);
        }

        /// <summary>
        /// 从系统缓存中载入配置数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T LoadCached<T>()
        {
            return LoadCached<T>(null);
        }

        /// <summary>
        /// 从缓存中清除配置数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        public static void RemoveCached<T>()
        {
            var chahe_key = string.Format("{0}.config", typeof(T).Name);
            CacheHelper.Remove(chahe_key);
        }
    }
}
